package edu.guet.server.service;

import edu.guet.server.mapper.SemesterMapper;
import edu.guet.server.mapper.UserMapper;
import edu.guet.server.model.SemesterStatistic.Student;
import edu.guet.server.model.User;
import edu.guet.server.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserService {
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SemesterMapper semesterMapper;

    public ResultAPI login(User user) {
        // 根据接收用户名密码查询数据库
        User userDB = userMapper.login(user);
        if (userDB!=null){
            Integer semesterId=userDB.getSemester_id();
            userDB.setCourse_id(semesterMapper.getCourseIdBysemId(semesterId));
            //将用户名和密码放入Map
            Map<String,String> map = new HashMap<String,String>();
            map.put("username",userDB.getUsername());
            map.put("password",userDB.getPassword());
            //使用包含用户名和密码的map生成Token
            String token = JwtTool.getToken(map);
            userDB.setToken(token);
            //返回添加了Token的user
           return ResultAPI.success(userDB,"登录成功！");
        }
        throw  new CustomizationException(ExceptionEnum.LOGIN_ERROR);
    }


    public ResultAPI register(User data) //用户注册
    {
        User user = userMapper.getUserByPhonenum(data.getPhone_num());
        //该手机号尚未注册
        if(user==null){
            userMapper.register(data);
            if(data.getUser_type().equals("student")){
                User u = userMapper.getUserByStuNumber(data.getStu_number());
                if(u!=null){return ResultAPI.error("该学号已注册！");}
                userMapper.addStu(data);
                //填写老师批量选课表中的学号对应的id
                userMapper.updateSemStuId(data);
            }
            return ResultAPI.success(data,"注册成功！");
        }else return ResultAPI.error("该手机或邮箱已注册！");
//        else throw new CustomizationException(ExceptionEnum.USER_EXIST);
    }

    public ResultAPI getUsername(String token) {
        Map<String, String> a = JwtTool.parseToken(token);
        if(a!=null)
        {
            return ResultAPI.success(a,"成功");
        }
        else throw new CustomizationException(ExceptionEnum.USER_EXIST);
    }

    public User getUser(Integer techId) {
        return userMapper.getUser(techId);
    }

    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
}
